<template>
  <a-card :bordered="false">
    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus" :disabled="isDisabledAuth('erpFinanceTravelReimbursementDetail:add')" :hidden="disabled || showFlowSubmitButton">新增</a-button>
      <a-button @click="syncAdd" type="primary" icon="vertical-align-bottom" :disabled="isDisabledAuth('erpFinanceTravelReimbursementDetail:sync')" :hidden="disabled || showFlowSubmitButton">同步信息到自驾公里数补助明细</a-button>
    </div>

    <!-- table区域-begin -->
    <div>
      <a-table
        ref="table"
        size="middle"
        :scroll="{x:scrollX}"
        bordered
        rowKey="key"
        :columns="columns"
        :components="draggableComponent"
        :dataSource="dataSource"
        :pagination="false"
        :loading="loading"
        :rowSelection="disabled?null:{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        :class="'j-table-force-nowrap'"
        @change="handleTableChange">
        <template slot="departurePlace" slot-scope="text">
          <div>{{ getPcaText(text) }}</div>
        </template>
        <template slot="targetPlace" slot-scope="text">
          <div>{{ getPcaText(text) }}</div>
        </template>
        <span slot="action" slot-scope="text, record">
          <a-button
            class="ruleButton"
            :ghost="true"
            type="primary"
            icon="edit"
            @click="handleEdit(record)"
            :hidden="disabled"
            :disabled="isDisabledAuth('erpFinanceTravelReimbursementDetail:edit')"
          />
          <template v-if="!showFlowSubmitButton">
          <a-divider type="vertical" :hidden="disabled"/>
          <a-popconfirm title="确定复制行吗?" @confirm="() => handleCopy(record)">
            <a-button
              class="ruleButton"
              :ghost="true"
              type="primary"
              icon="copy"
              :hidden="disabled"
              :disabled="isDisabledAuth('erpFinanceTravelReimbursementDetail:copy')"/>
          </a-popconfirm>
          <a-divider type="vertical" :hidden="disabled"/>
          <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.key)">
            <a-button
              class="ruleButton"
              :ghost="true"
              type="primary"
              icon="delete"
              :hidden="disabled"
              :disabled="isDisabledAuth('erpFinanceTravelReimbursementDetail:delete')"/>
          </a-popconfirm>
        </template>
        </span>
      </a-table>
    </div>

    <erp-finance-travel-reimbursement-detail-modal ref="modalForm" @ok="modalFormOk" @dataOne="dataOne" :showFlowSubmitButton="showFlowSubmitButton" :dateilType="dateilType"></erp-finance-travel-reimbursement-detail-modal>

    <!-- 项目详情开始 -->
    <erp-project-report-modal  ref="projectForm"></erp-project-report-modal>
    <!-- 项目详情结束 -->
  </a-card>
</template>

<script>

import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import ErpFinanceTravelReimbursementDetailModal from './ErpFinanceTravelReimbursementDetailModal'
import { DisabledAuthFilterMixin } from '@/mixins/DisabledAuthFilterMixin'
import AuditModal from '@/views/scy/components/AuditModal'
import { filterObj } from '@/utils/util'
import { getAction } from '@/api/manage'
import Vue from 'vue'
import address from '@/components/AddressChoice/address.js'
import { filterMultiDictText, initDictOptions } from '@/components/dict/JDictSelectUtil'
import Area from '@/components/_util/Area'
import { DragResizable } from '@/mixins/DragResizable'
  export default {
    name: 'ErpFinanceTravelReimbursementDetailList',
    mixins: [mixinDevice, DisabledAuthFilterMixin,DragResizable],
    components: {
      ErpProjectReportModal: () => import('@/views/erp/report/project/modules/ErpProjectReportModal'),
      ErpFinanceTravelReimbursementDetailModal,
      AuditModal
    },
    props: {
      // 表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      showFlowSubmitButton: {
        type: Boolean,
        default: false,
        required: false
      },
      teamId: {
        type: String,
        default: '',
        required: false
      },
      companyId: {
        type: String,
        default: '',
        required: false
      },
      isRelProject: {
        type: String,
        default: '',
        required: false
      },
    },
    data () {
      return {
        address,
        params: {
          billId: null
        },
        /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
        queryParam: {},
        /* 数据源 */
        dataSource: [],
        /* 分页参数 */
        ipagination: {
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30', '50', '100', '200'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        /* 排序参数 */
        isorter: {
          column: 'createTime',
          order: 'desc'
        },
        /* 筛选参数 */
        filters: {},
        /* table加载状态 */
        loading: false,
        /* table选中keys */
        selectedRowKeys: [],
        /* table选中records */
        selectionRows: [],
        /* 查询折叠 */
        toggleSearchStatus: false,
        /* 高级查询条件生效状态 */
        superQueryFlag: false,
        /* 高级查询条件 */
        superQueryParams: '',
        /** 高级查询拼接方式 */
        superQueryMatchType: 'and',
        iconStyle: { 'font-size': '18px', 'cursor': 'pointer' },
        colsettings: ':colsettings',
        description: '差旅报销单明细管理页面',
        // 表头
        columns: [],
        // 列设置
        settingColumns: [],
        // 报销详情明细
        defColumns: [
          {
            title: '序号',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },
          {
            title: '项目名称',
            align: 'center',
            dataIndex: 'projectId',
            width: 180,
            ellipsis: true,
            customRender: (text, r) => {
              if (!text) {
                return ''
              } else {
                return <a v-on:click={(e) => this.onDetail(text)}>{ filterMultiDictText(this.dictOptions['projectId'], text + '') }</a>;
              }
            }
          },
          {
            title: '项目编号',
            align: 'center',
            dataIndex: 'projectCode',
            width: 180,
            ellipsis: true
          },
          {
            title: '业绩归属年度',
            align: 'center',
            dataIndex: 'attributionYear',
            width: 180,
            ellipsis: true,
          },
          // {
          //   title:'项目阶段',
          //   align:"center",
          //   dataIndex: 'projectType',
          //   ellipsis: true,
          //   customRender: (text,r) => {
          //     if (!text) {
          //       return ''
          //     } else {
          //       return filterMultiDictText(this.dictOptions['projectType'], text + '')
          //     }
          //   }
          // },
          {
            title: '任务分类',
            align: 'center',
            dataIndex: 'taskId',
            width: 180,
            ellipsis: true,
            customRender: (text, r) => {
              if (!text) {
                return ''
              } else {
                return filterMultiDictText(this.dictOptions['taskId'], text + '')
              }
            }
          },
          {
            title: '任务说明',
            align: 'center',
            width: 180,
            ellipsis: true,
            dataIndex: 'taskDescription'
          },
          // {
          //   title:'费用所属年度',
          //   align:"center",
          //   dataIndex: 'teamYear',
          //   ellipsis: true,
          //   customRender: (text) => {
          //     if (!text) {
          //       return ''
          //     } else {
          //       return filterMultiDictText(this.dictOptions['teamYear'], text + '')
          //     }
          //   }
          // },
          // {
          //   title:'费用所属团队',
          //   align:"center",
          //   dataIndex: 'teamId',
          //   ellipsis: true,
          //   customRender: (text) => {
          //     if (!text) {
          //       return ''
          //     } else {
          //       return filterMultiDictText(this.dictOptions['teamId'], text + '')
          //     }
          //   }
          // },
          {
            title: '出发时间',
            align: 'center',
            dataIndex: 'setOutTime',
            width: 180,
            ellipsis: true,
            customRender: (text, r) => {
              return !text ? '' : (text.length > 13 ? text.substr(0, 13) : text)
            }
          },
          {
            title: '回程时间',
            align: 'center',
            dataIndex: 'backTime',
            width: 180,
            ellipsis: true,
            customRender: (text, r) => {
              return !text ? '' : (text.length > 13 ? text.substr(0, 13) : text)
            }
          },
          {
            title: '出差天数',
            align: 'center',
            width: 180,
            dataIndex: 'days',
            ellipsis: true
          },
          {
            title: '报销内容',
            width: 180,
            align: 'center',
            dataIndex: 'feeType',
            ellipsis: true,
            customRender: (text, r) => {
              if (!text) {
                return ''
              } else {
                var feeType = filterMultiDictText(this.dictOptions['feeType'], text + '');
                return feeType
              }
            }
          },
          {
            title: '交通方式',
            width: 180,
            align: 'center',
            dataIndex: 'transportMode',
            ellipsis: true,
            customRender: (text, r) => {
              if (!text) {
                return ''
              } else {
                var transportMode = filterMultiDictText(this.dictOptions['transportMode'], text + '');
                return transportMode
              }
            }
          },
          {
            title: '出发地点',
            align: 'center',
            dataIndex: 'departurePlace',
            ellipsis: true,
            width: 350,
            scopedSlots: { customRender: 'departurePlace' }
          },
          {
            title: '到达地点',
            align: 'center',
            dataIndex: 'targetPlace',
            width: 350,
            ellipsis: true,
            scopedSlots: { customRender: 'targetPlace' }
          },
          {
            title: '发票类型',
            align: 'center',
            dataIndex: 'isSpecial',
            width: 180,
            ellipsis: true,
            customRender: (text, r) => {
              if (!text) {
                return ''
              } else {
                var isSpecial = filterMultiDictText(this.dictOptions['isSpecial'], text + '');
                return isSpecial
              }
            }
          },
          {
            title: '报销金额（元）',
            align: 'center',
            dataIndex: 'amount',
            width: 180,
            ellipsis: true
          },
          {
            title: '税费金额（元）',
            align: 'center',
            dataIndex: 'taxation',
            width: 180,
            ellipsis: true
          },
          {
            title: '未税金额（元）',
            align: 'center',
            dataIndex: 'untaxedAmount',
            width: 180,
            ellipsis: true
          },
          {
            title: '税率(%)',
            align: 'center',
            dataIndex: 'taxRate',
            width: 180,
            ellipsis: true
          },
          // {
          //   title: '备注',
          //   align: 'center',
          //   dataIndex: 'remark',
          //   width: 150,
          //   ellipsis: true
          // },
          {
            title: '操作',
            dataIndex: 'action',
            align: 'center',
            fixed: 'right',
            width: 147,
            scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action' }
          }
        ],
        url: {
          list: '/api/erp/finance/travel/erpFinanceTravelReimbursementDetail/allList',
          queryByProjectId: '/api/erp/project/report/erpProjectReport/queryById'
        },
        dictOptions: {},
        superFieldList: [],
        dateilType: true,
        reimbursementDetailType: 1
      }
    },
    created() {
      this.pcaData = new Area()
      // 加载数据字典信息
      this.initDictConfig();
      if (!this.disableMixinCreated) {
        this.initColumns()
      }
      this.fieldChange(this.isRelProject)
      if (this.disabled) {
        this.defColumns.pop()
        // this.defColumns.map(val => {
        //   delete val.width
        // })
      }
      this.customKey = 'columns'
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          '0': '待提交',
          '1': '待审核',
          '2': '已审核'
        }
        return statusMap[status] || status
      },
      statusTypeFilter(type) {
        const statusTypeMap = {
          '0': 'success',
          '1': 'success',
          '2': 'success'
        }
        return statusTypeMap[type] || 'success'
      }
    },
    watch: {
      isRelProject(val){
        this.fieldChange(val)
      }
    },
    methods: {
      fieldChange(val){
        if(this.columns.length){
          if(val==1){
            // if(this.columns.filter(v => v.dataIndex=='taskDescription' || v.dataIndex=='attributionYear').length!=0){
            if(this.columns.filter(v => v.dataIndex=='taskDescription').length!=0){
              if(this.columns.findIndex(v => v.dataIndex=='taskDescription')>0){
                this.columns.splice(this.columns.findIndex(v => v.dataIndex=='taskDescription'),1)
              }
            // #紧急迭代,显示业绩归属年度
              // if(this.columns.findIndex(v => v.dataIndex=='attributionYear')>0){
              //   this.columns.splice(this.columns.findIndex(v => v.dataIndex=='attributionYear'),1)
              // }
            }
          } else {
            if(this.columns.filter(v => v.dataIndex=='taskDescription').length==0){
              this.columns.splice(4,0,{
                title: '任务说明',
                align: 'center',
                width: 180,
                ellipsis: true,
                dataIndex: 'taskDescription'
              })
              // this.columns.splice(5,0,{
              //   title: '业绩归属年度',
              //   align: 'center',
              //   dataIndex: 'attributionYear',
              //   width: 180,
              //   ellipsis: true,
              //   customRender: (text, r) => {
              //     if (!text) {
              //       return ''
              //     } else {
              //       var attributionYear = filterMultiDictText(this.dictOptions['attributionYear'], text + '');
              //       return attributionYear
              //     }
              //   }
              // })
            }
          }
        }
      },
      getPcaText (text) {
        if (!text) {
          return false
        }
        var areaList = text.split(',')
        var areaText = ''
        this.address.map(value => {
          if (areaList[0] && areaList[0] == value.code) {
            areaText = areaText + value.name + '/'
            if (value && value.children && value.children.length) {
              value.children.map(val => {
                if (areaList[1] && areaList[1] == val.code) {
                  areaText = areaText + val.name + '/'

                  if (val && val.children && val.children.length) {
                    val.children.map(va => {
                      if (areaList[2] && areaList[2] == va.code) {
                        areaText = areaText + va.name
                      }
                    })
                  }
                }
              })
            }
          }
        })
        return areaText
      },
      initDictConfig() {
        initDictOptions('erp_omc_team_manager,alias_name,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'teamId', res.result)
          }
        })
        initDictOptions('erp_omc_project,project_name,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'projectId', res.result)
          }
        })
        initDictOptions('erp_omc_project_task,category_name,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'taskId', res.result)
          }
        })
        initDictOptions('yjgsnd').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'attributionYear', res.result)
          }
        })
        initDictOptions('reimbursement_content').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'feeType', res.result)
          }
        })
        initDictOptions('transportation').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'transportMode', res.result)
          }
        })
        initDictOptions('invoice_type').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'isSpecial', res.result)
          }
        })
        initDictOptions('tdnd_type').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'teamYear', res.result)
          }
        })
        // initDictOptions('project_status').then((res) => {
        //   if (res.success) {
        //     this.$set(this.dictOptions, 'projectType', res.result)
        //   }
        // })
      },
      getSelectedRowKeys() {
        var ids = ''
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ','
        }
        return ids
      },
      loadData(arg, id) {
        // 清空列表选中
        this.onClearSelected()
        if (!this.url.list) {
          this.$message.error('请设置url.list属性!')
          return
        }
        // 加载数据 若传入参数1则加载第一页的内容
        if (arg === 1) {
          this.ipagination.current = 1
        }
        this.params = this.getQueryParams() // 查询条件
        if (id) {
          this.params.billId = id
        }
        this.params.detailType = this.reimbursementDetailType
        this.loading = true
        getAction(this.url.list, this.params).then(res => {
          if (res.success) {
            // update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
            this.dataSource = res.result.records || res.result
            this.dataSource.forEach((item, index) => {
              item.key = index
            })
            this.onData()
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
            // 判断是否当前页没有数据且不为第一页
            if (this.dataSource.length == 0 && this.ipagination.current != 1) {
              this.ipagination.current = this.ipagination.current - 1
              this.loadData(this.ipagination.current - 1);
            }
            // update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          }
          if (res.code === 510) {
            this.$message.warning(res.message)
          }
          this.loading = false
        })
      },
      getQueryParams() {
        // 获取查询条件
        let sqp = {}
        if (this.superQueryParams) {
          sqp['superQueryParams'] = encodeURI(this.superQueryParams)
          sqp['superQueryMatchType'] = this.superQueryMatchType
        }
        var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)
        param.field = this.getQueryField()
        param.pageNo = this.ipagination.current
        param.pageSize = this.ipagination.pageSize
        return filterObj(param)
      },
      getQueryField() {
        // TODO 字段权限控制
        var str = 'id'
        this.columns.forEach(function (value) {
          // 多表头字段
          if (value.dataIndex == null && value.dataIndex === undefined) {
            value.children.forEach(function (item) {
              str += ',' + item.dataIndex.replace('_dictText', '')
            })
          } else {
            str += ',' + value.dataIndex
          }
        })
        return str
      },
      onSelectChange(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectionRows = selectionRows
      },
      onClearSelected() {
        this.selectedRowKeys = []
        this.selectionRows = []
      },
      searchQuery() {
        this.loadData(1)
      },
      superQuery() {
        this.$refs.superQueryModal.show()
      },
      handleDelete: function (key) {
        if (this.dataSource.length == 1) {
          this.dataSource = []
          this.onData()
          return
        }
        this.dataSource.splice(key, 1);
        this.dataSource.forEach((item, index) => {
          item.key = index
        })
        this.onData()
      },
      handleEdit: function (record) {
        // debugger;
        if (this.isRelProject == '1' && !this.companyId) {
          this.$message.error('请选择申请公司!')
          return false
        }
        if (this.isRelProject == '1' && !this.teamId) {
          this.$message.error('请选择费用所属团队!')
          return false
        }
        this.$refs.modalForm.edit(record,this.isRelProject)
        this.$refs.modalForm.title = '编辑'
        this.$refs.modalForm.disableSubmit = false
      },
      handleAdd: function () {
        console.log('执行了--');
        if (this.isRelProject == '1' && !this.companyId) {
          this.$message.error('请选择申请公司!')
          return false
        }
        if (this.isRelProject == '1' && !this.teamId) {
          this.$message.error('请选择费用所属团队!')
          return false
        }
        this.$refs.modalForm.add(this.isRelProject)
        this.$refs.modalForm.title = '新增'
        this.$refs.modalForm.disableSubmit = false
      },
      handleTableChange(pagination, filters, sorter) {
        // 分页、排序、筛选变化时触发
        this.filters = {}
        if (Object.keys(filters).length > 0) {
          for (let key in filters) {
            let value = filters[key].join(',')
            if (value) {
              if (key.indexOf('_dictText') != -1) {
                key = key.substring(0, key.indexOf('_dictText'))
              }
              this.filters[key] = value
            }
          }
        }
        if (Object.keys(sorter).length > 0) {
          this.isorter.column = sorter.field
          this.isorter.order = sorter.order == 'ascend' ? 'asc' : 'desc'
        }
        this.ipagination = pagination
        this.loadData()
      },
      modalFormOk() {
        // 新增/修改 成功时，重载列表
        this.loadData()
        // 清空列表选中
        this.onClearSelected()
      },
      initColumns() {
        // 权限过滤（列权限控制时打开，修改第二个参数为授权码前缀）
        // this.defColumns = colAuthFilter(this.defColumns,'testdemo:');
        if (this.defColumns) {
          var key = this.$route.name + this.colsettings
          let colSettings = Vue.ls.get(key)
          if (colSettings == null || colSettings == undefined) {
            let allSettingColumns = []
            this.defColumns.forEach(function (item, i, array) {
              allSettingColumns.push(item.dataIndex)
            })
            this.settingColumns = allSettingColumns
            this.columns = this.defColumns
          } else {
            Vue.ls.set(key, colSettings, 7 * 24 * 60 * 60 * 1000)
            this.settingColumns = colSettings
            const cols = this.defColumns.filter(item => {
              if (item.key == 'rowIndex' || item.dataIndex == 'action') {
                return true
              }
              if (colSettings.includes(item.dataIndex)) {
                return true
              }
              return false
            })
            this.columns = cols
          }
        }
      },
      dataOne(data, flag) {
        if (flag) {
          this.dataSource.push(data)
          this.dataSource.forEach((item, index) => {
            item.key = index
          })
        } else {
          this.dataSource.splice(data.key, 1, data);
        }
        this.onData()
      },
      submitForm() {
        return this.dataSource
      },
      onData() {
        this.$emit('travelDetailData', this.dataSource);
      },
      handleCopy: function (record) {
        let data = Object.assign({}, record);
        this.dataOne(data, true)
      },
      syncAdd() {
        if (this.selectedRowKeys.length <= 0) {
          this.$message.warning('请选择一条记录！');
        } else {
          let syncList = []
          for (var a = 0; a < this.selectedRowKeys.length; a++) {
            let item = Object.assign({}, this.dataSource[this.selectedRowKeys[a]]);
            this.$set(item, 'feeType', null)
            this.$set(item, 'transportMode', null)
            this.$set(item, 'isSpecial', null)
            this.$set(item, 'amount', null)
            this.$set(item, 'taxation', null)
            this.$set(item, 'untaxedAmount', null)
            this.$set(item, 'remark', null)
            this.$set(item, 'detailType', '2')
            syncList.push(item)
          }
          var that = this;
          this.$confirm({
            title: '确认同步',
            content: '是否同步选中数据?',
            onOk: function () {
              that.$emit('syncAdd', syncList);
              that.selectedRowKeys = []
            }
          });
        }
      },
      onDetail(id) {
        const that = this
        this.$nextTick(() => {
          getAction(this.url.queryByProjectId, { id: id }).then((res) => {
            if (res.success) {
              const model = res.result
              that.$refs.projectForm.getDetail(model);
              that.$refs.projectForm.title = '项目一览表';
            }
          })
        })
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>
